//
//  FriendViewController.m
//  MooreDoll
//
//  Created by Joe on 2014/11/24.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "FriendViewController.h"
#import "FreindCell.h"
#import "FriendSearchCell.h"
#import "AddFriendCell.h"
#import "AddressBookViewController.h"
#import "AppDelegate.h"
#import "RoomViewController.h"
#import "MessageViewController.h"
#import "Reachability.h"
@interface FriendViewController ()

@end

@implementation FriendViewController
@synthesize Array_myRoster,table_FriendList,Array_Friend,Array_toy;


#pragma mark Life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //從server比對本機的名冊後才讀取好友名單
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadRoster) name:@"RosterSync" object:nil];

    //Tank{
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    Array_Friend = [[NSMutableArray alloc] init];
    Array_toy    = [[NSMutableArray alloc] init];
    //}
    
    [self loadRoster];
}
- (IBAction)addNewToy:(id)sender {
    AddMooreDollViewController *addMooreDollVC = [self.storyboard instantiateViewControllerWithIdentifier:@"AddMooreDollViewController"];
    [self.navigationController pushViewController:addMooreDollVC animated:YES];
}

//Tank{
-(void)viewWillAppear:(BOOL)animated
{
    [self checkForNetwork];
}
- (void)checkForNetwork
{
    // check if we've got network connectivity
    if ([XMPPSharedInstance sharedInstance].state == 0) {
        
        Reachability *myNetwork = [Reachability reachabilityWithHostName:@"google.com"];
        NetworkStatus myStatus = [myNetwork currentReachabilityStatus];
        
        switch (myStatus) {
            case NotReachable:
                NSLog(@"There's no internet connection at all. Display error message now.");
                break;
                
            case ReachableViaWWAN:
                NSLog(@"We have a 3G connection");
                [self checkConnect];
                
                break;
                
            case ReachableViaWiFi:
                NSLog(@"We have WiFi.");
                [self checkConnect];
                
                break;
                
            default:
                break;
        }

    }
}
-(void)checkConnect
{
    
    
    //檢查有沒有儲存帳號密碼 且密碼不是未設定
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"account"]!=nil && [[NSUserDefaults standardUserDefaults]objectForKey:@"password"] != nil && ![[[NSUserDefaults standardUserDefaults]objectForKey:@"password"] isEqualToString:@"01234"]) {
        
        
            //檢查目前網路狀態
            if ([XMPPSharedInstance sharedInstance].state == 0) {
                
                //這邊註冊了登入後的 delegate
                [XMPPSharedInstance sharedInstance].stateDelegate = self;
                
                //執行登入
                [[XMPPSharedInstance sharedInstance] loginXMPP];
            }
        
        
       
        
    }else
    {
        //如果沒有儲存帳號 就轉到登入畫面
        LoginOrRegistViewController *loginVC = [self.storyboard instantiateViewControllerWithIdentifier:@"LoginOrRegistViewController"];
        [self.navigationController pushViewController:loginVC animated:NO];
        
    }
    
}
//}



//推出側邊欄
- (IBAction)openDrawer:(id)sender {
    [self.menuContainerViewController toggleLeftSideMenuCompletion:nil];
}



//Tank{
#pragma mark connectStateDelegate 連線的delegate
-(void)connectState:(int)state
{
    //因為這邊delegate 是在背景執行時觸發 但因為我們有做切換畫面 所以要回到主線程 不然會出問題
    dispatch_async(dispatch_get_main_queue(), ^{
        
        switch (state) {
            case 0:
                NSLog(@"連線中斷");
                break;
            case 1:
                NSLog(@"進行連線");
                break;
            case 2:
                NSLog(@"連線成功");
                break;
            default:
                break;
        }
    });
    
}
//}

-(void)loadRoster
{
    
    [Array_toy removeAllObjects];
    [Array_Friend removeAllObjects];
    
    //取得好友列表 再依狀態去判斷 要對應娃娃還是朋友
    [[DBManage getRoster] enumerateObjectsUsingBlock:^(FriendRoster * roster, NSUInteger idx, BOOL *stop) {
        
        if ([roster.type isEqualToNumber:[NSNumber numberWithInt:0]]) {
            [Array_toy addObject:roster];
        }else
        {
            [Array_Friend addObject:roster];
        }
    }];
    
    [table_FriendList reloadData];
    
    
}
#pragma mark UITableViewDataSource and UITableviewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //暫時回傳好友數量，等有MD跟group再針對section設計
    //return Array_myRoster.count;
    if (section ==0 )
    {
        //如果沒有 娃娃 就回傳一個 並且說無娃娃 是否需新增娃娃
        if (Array_toy.count == 0) {
            return 1;
        }

        return Array_toy.count;
    }else
    {
        return Array_Friend.count;

    }

    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //回傳該Cell的高度
    UITableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"FreindCell" owner:self options:nil] objectAtIndex:0];
    return cell.frame.size.height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *sectionName;
    if (section ==0)
        sectionName = [NSString stringWithFormat:@"toy %i",Array_toy.count];
    else
        sectionName = [NSString stringWithFormat:@"user %i",Array_Friend.count];
 
    return sectionName;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //暫時只設計好友cell，MD跟Group出來在新增不同的cell
    FreindCell *friendCell = [tableView dequeueReusableCellWithIdentifier:@"FreindCell"];
    
    if (indexPath.section == 0)
    {
        if (Array_toy.count == 0) {
            
            if (friendCell == nil)
            {
                friendCell = [[[NSBundle mainBundle] loadNibNamed:@"FreindCell" owner:self options:nil] objectAtIndex:0];
            }
            [friendCell setcellWitNoHaveToy];

            
        }else
        {
            if (friendCell == nil)
            {
                friendCell = [[[NSBundle mainBundle] loadNibNamed:@"FreindCell" owner:self options:nil] objectAtIndex:0];
            }
            FriendRoster *roster = [Array_toy objectAtIndex:indexPath.row];
            [friendCell setCellWithRoster:roster];

        }
    }
    else
    {
        if (friendCell == nil)
        {
            friendCell = [[[NSBundle mainBundle] loadNibNamed:@"FreindCell" owner:self options:nil] objectAtIndex:0];
        }
        FriendRoster *roster = [Array_Friend objectAtIndex:indexPath.row];
        [friendCell setCellWithRoster:roster];

    }
    
    return friendCell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    FreindCell *friendCell = (FreindCell *)[tableView cellForRowAtIndexPath:indexPath];
    [DBManage whoseRoom:friendCell.cellsRoster.jid completionBlock:^(Room *room) {
        
        
    } failureBlock:^(BOOL noRoom) {
        
    }];
    
    
    //取得聊天室資訊
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"owner == %@",friendCell.cellsRoster.jid];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ChatRoom" inManagedObjectContext:managedObjectContext];
    [fetch setEntity:entity];
    [fetch setPredicate:predicate];
    NSArray *fetchRoom = [managedObjectContext executeFetchRequest:fetch error:nil];
    
    ChatRoom *chatRoom;
    
    
    if (fetchRoom.count==0)
    {
        //如果找不到該好友的聊天室，創建一個
        chatRoom = [NSEntityDescription insertNewObjectForEntityForName:@"ChatRoom" inManagedObjectContext:managedObjectContext];
//        chatRoom.displayName = friendCell.cellsRoster.nickeName;
//        chatRoom.owner = friendCell.cellsRoster.jid;
//        [friendCell.cellsRoster addOwnerObject:chatRoom];
//        
        [managedObjectContext save:nil];
    }
    else
    {
        //如果找到，取得該聊天室
        chatRoom = [fetchRoom objectAtIndex:0];
    }
    
    
    //切換messageViewController，並把room's info pass給messageViewController
    UINavigationController *navi = [self.tabBarController.childViewControllers objectAtIndex:1];
    MessageViewController *VC_message;
    
    for (UIViewController *VC in navi.viewControllers)
    {
        if ([VC isKindOfClass:[MessageViewController class]])
        {
            VC_message = (MessageViewController *)VC;
            break;
        }
    }
    
    VC_message.chatRoomFromFriendVC = chatRoom;
    self.tabBarController.selectedIndex =1;
    
}


@end
